<?php

namespace app\common\model\info;
use app\common\model\BaseModel;
use app\common\model\lawyer\Lawyer;
use app\common\model\user\User;
use app\common\repositories\info\InfoRepository;
use app\common\repositories\system\SystemCityRepository;

class Info extends BaseModel
{

    public static function tablePK(): ?string
    {
        return 'info_id';
    }

    public static function tableName(): string
    {
        return 'info';
    }


    public function getCityAttr()
    {
        return app()->make(SystemCityRepository::class)->getCompleteAddress($this->city_id,' ');
    }

    public function getTypeNameAttr()
    {
        return InfoRepository::INFO_TYPE[$this->getAttr('type')] ??'';
    }


    public function user()
    {
        return $this->hasOne(User::class,'uid','uid');
    }


    public function getInfoIdAttr($value)
    {
        if(
            $this->type != 7 ||
            $this->status == 3 ||
            $this->status == -1 ||
            !$this->auto_end_time ||
            $this->auto_end_time < time()
        ) return $value;

        app()->make(InfoRepository::class)->orderGone($value);

        return $value;
    }


    public function getCateAttr($value)
    {
        if(in_array($this->getAttr('type'),[0,1])){
            return $value ? explode(',',$value) : [];
        }

        return $value;
    }



    public function getQuestionContentAttr()
    {
        $q =  Question::getDB()->where('info_id',$this->info_id,)
            ->where('type',2)->order('question_id desc')->find();
        if(!$q){
            return null;
        }
        $q['lawyer'] = Lawyer::getDB()->where(['lawyer_id'=>$q['lawyer_id']])->field('lawyer_id,name,avatar')->find();
        return $q;
    }


    public function getQuestionCountAttr()
    {
        return Question::getDB()->where('info_id',$this->info_id,)
            ->where('type',2)->count();
    }

}